import axios from 'axios';
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { store } from "../store/store";

// 定义接口返回数据的通用结构
interface ApiResponse<T = any> {
  code: number;
  data: T;
  message: string;
  token?: string;
}

class Request {
  private instance: AxiosInstance;

  constructor(baseURL: string) {
    this.instance = axios.create({
      baseURL,
      timeout: 10000,
      headers: {
        'Content-Type': 'application/json',
      },
    });

    // 请求拦截器
    this.instance.interceptors.request.use(
      (config) => {
        // 可在此添加token等全局headers
        const token = store.getState().auth.token;
        if (token) {
          config.headers.Authorization = token;
        }
        return config;
      },
      (error) => Promise.reject(error)
    );

    // 响应拦截器
    this.instance.interceptors.response.use(
      (response: AxiosResponse<ApiResponse>) => {
        // 处理业务逻辑错误（如code非200）
        if (response.data.code !== 200) {
          return Promise.reject(new Error(response.data.message || 'Error'));
        }
        return response.data; // 直接返回有用的data字段
      },
      (error) => {
        // 统一错误处理
        if (error.response?.status === 401) {
          // 跳转登录页等操作
        }
        return Promise.reject(error);
      }
    );
  }

  public get<T>(url: string, config?: AxiosRequestConfig): Promise<ApiResponse<T>> {
    return this.instance.get(url, config);
  }

  public post<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ApiResponse<T>> {
    return this.instance.post(url, data, config);
  }
}

// 根据环境变量切换baseURL
const baseURL = 'https://www.liqiantw.icu:3000';

export const request = new Request(baseURL);